package com.liuzhilong.infrastructure.framework.netty.echo.server;

import com.liuzhilong.infrastructure.framework.netty.echo.server.handle.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

@Setter
@Accessors(chain = true)
@Slf4j
public class EchoServer {

    private String host;
    private int port;
    private  ServerBootstrap serverBootstrap;


    public void start(){
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup(20);

        this.serverBootstrap=  new ServerBootstrap()
                .group(boss, work)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        ch.pipeline().addLast("decoder", new StringDecoder());
                        ch.pipeline().addLast("encoder", new StringEncoder());
                        ch.pipeline().addLast(new EchoServerHandler());

                    }
                });

        ChannelFuture future;
        try {
            log.info("正在启动服务器，绑定到端口[{}]",port);

            future = serverBootstrap.bind(port);
            //同步
            future.sync();
        } catch (Exception e) {
            log.error("NettyRemotingServer bind fail {}, exit",e.getMessage(), e);
            throw new RuntimeException(String.format("NettyRemotingServer bind %s fail", port));
        }
        if (future.isSuccess()) {
            log.info("NettyRemotingServer bind success at port : {}",port);
        } else if (future.cause() != null) {
            throw new RuntimeException(String.format("NettyRemotingServer bind %s fail", port), future.cause());
        } else {
            throw new RuntimeException(String.format("NettyRemotingServer bind %s fail", port));
        }
    }




}
